package com.scm.core.interceptor;

import java.lang.annotation.Annotation;
import java.util.Date;
import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.scm.biz.bean.OperateLog;
import com.scm.biz.service.OperateLogService;

public class LogInterceptor implements HandlerInterceptor {
	@Autowired
	OperateLogService operateLogService;
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse arg1, Object handler, Exception arg3)
			throws Exception {
		if(HandlerMethod.class.isAssignableFrom(handler.getClass())){  
			HandlerMethod handlerMethod = (HandlerMethod) handler;  
			LogConfig logConfig = handlerMethod.getMethodAnnotation(LogConfig.class);
			if(logConfig !=null && request.getSession().getAttribute("isLogin") !=null){
				OperateLog operateLog = new OperateLog();
				operateLog.setCode(handlerMethod.getBeanType()+"."+handlerMethod.getMethod().getName());
				operateLog.setCreatedAt(new Date());
				operateLog.setDescription(logConfig.description());
				operateLog.setModuleCode(logConfig.operationModule().toString());
				operateLog.setOperator(request.getSession().getAttribute("userCode").toString());
				String params = "";
				Enumeration<String> paramKeys = request.getParameterNames();
				String key = "";
				while(paramKeys.hasMoreElements()){
					key = paramKeys.nextElement();
					params = params +"&"+ key+":"+request.getParameter(key);
				}
				operateLog.setParams(params);
				operateLogService.insert(operateLog);
			}
	      
	      }
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object handler, ModelAndView mv) throws Exception {
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse arg1,
			Object handler) throws Exception {
		// TODO Auto-generated method stub
		request.getSession().setAttribute("randomId", UUID.randomUUID().toString());
		
		return true;
	}
}